
import requests
from cozepy import Coze, TokenAuth, Message, MessageObjectString, COZE_CN_BASE_URL


from func.log.default_log import DefaultLog
from func.config.default_config import defaultConfig
from cozepy import MessageType


# CozeBot 类
class CozeBot:
    def __init__(self):
        config = defaultConfig().get_config()
        self.coze_api_token = config['coze']['api_key']
        self.file_upload_url = config['coze']['file_upload_url']
        self.bot_id = config['coze']['bot_id']  # 需要在初始化时提供
        self.user_id = config['coze']['user_id']  # 用户ID，可以根据需要调整
        self.base_url = COZE_CN_BASE_URL        
        self.logger = DefaultLog().getLogger()


        # 初始化Coze API
        self.coze = Coze(auth=TokenAuth(token=self.coze_api_token), base_url=COZE_CN_BASE_URL)

    def upload_file(self, file_path):
        """
        上传文件到Coze并返回文件ID
        """
        url = self.file_upload_url
        headers = {
            'Authorization': f'Bearer {self.coze_api_token}'
        }

        with open(file_path, 'rb') as file:
            files = {'file': file}
            response = requests.post(url, headers=headers, files=files)

        if response.status_code == 200:
            data = response.json()
            file_id = data.get('data', {}).get('id', None)
            if file_id:
                return file_id
            else:
                print(f"未找到文件ID: {file_path}")
                return None
        else:
            print(f"上传失败，状态码：{response.status_code}，文件: {file_path}")
            return None

    def chat_with_coze(self, message_text, file_id=''):
        """
        使用Coze API与聊天机器人进行对话，并获取响应
        """
        additional_messages = [Message.build_user_question_text(message_text)]

        # 如果 file_id 不为空，才构造 file 对象
        if file_id:
            additional_messages.append(Message.build_user_question_objects([MessageObjectString.build_file(file_id=file_id)]))

        chat_poll = self.coze.chat.create_and_poll(
            bot_id=self.bot_id,
            user_id=self.user_id,
            additional_messages=additional_messages
        )


        response_str = ""

        for message in chat_poll.messages:
            if message.type == MessageType.ANSWER:
                response_str = message.content

        if response_str:
            return response_str
        else:
            print(f"未获取到回复，文件: {file_id}")
            return None




